<?php


namespace app\api\controller;


use app\admin\controller\admin\Admin;
use app\common\model\AdminAdmin;
use app\common\model\RecruitCustomer;
use app\common\model\RecruitCustomerBody;
use app\common\model\RecruitCustomerPhone;
use app\common\model\SchoolCustomerSource;
use app\common\model\SchoolTeamTask;
use app\common\model\SchoolWorkerTask;
use app\common\model\StudyStudentList;
use think\facade\Db;

class Recruit
{
    /**
     * 招生人员登陆
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recruitLogin()
    {
        //验证用户
        $data = input('');
        $admin = AdminAdmin::where([
            'mobile' => trim($data['mobile']),
            'password' => set_password(trim($data['password'])),
            'status' => 1
        ])->find();
        if(!$admin)   resReturn('', '用户名密码错误', 101);
        $role = dataFind('bl_admin_admin_role', [
            'admin_id' => $admin['id'],
        ], '*', 'id desc');
        if (!in_array($role['role_id'], [4,5,7,6,9])) resReturn('', '用户身份错误', 101);
        $admin['role'] = $role;
        resReturn($admin);
    }

    /**
     * 招生人员主页
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recruitIndex()
    {
        $admin_id = input('param.admin_id');

        $topId = Db::table('bl_admin_admin')->where(['id'=>$admin_id])->value('top_id');
        if (!$topId){//团队
            $admin = AdminAdmin::where('top_id', $admin_id)->column('id');

            array_push($admin,(int)$admin_id);
            // 获取本月信息
            $task = SchoolTeamTask::where('admin_id', $admin_id)
                ->where('month', toDate(time(), 'Y-m'))
                ->find();
            $month_count = RecruitCustomer::whereIn('admin_id', $admin)
                ->whereTime('deal_time', 'month')
                ->count();
            $month_price = RecruitCustomer::whereIn('admin_id', $admin)
                ->whereTime('deal_time', 'month')
                ->sum('deal_price');
            $all_count = RecruitCustomer::whereIn('admin_id', $admin)
//                ->where('deal_price', '>', 0)
                ->count();
            $all_price = RecruitCustomer::whereIn('admin_id', $admin)
//                ->where('deal_price', '>', 0)
                ->sum('deal_price');
        }else{
            // 获取本月信息
            $task = SchoolWorkerTask::where('admin_id', $admin_id)
                ->where('month', toDate(time(), 'Y-m'))
                ->find();
            $month_count = RecruitCustomer::where('admin_id', $admin_id)
                ->whereTime('deal_time', 'month')
                ->count();
            $month_price = RecruitCustomer::where('admin_id', $admin_id)
                ->whereTime('deal_time', 'month')
                ->sum('deal_price');
            $all_count = RecruitCustomer::where('admin_id', $admin_id)
//                ->where('deal_price', '>', 0)
                ->count();
            $all_price = RecruitCustomer::where('admin_id', $admin_id)
//                ->where('deal_price', '>', 0)
                ->sum('deal_price');
        }
        if ($task) {
            $rate = bcdiv($month_price,$task['task_num'],4) * 100;
        } else {
            $rate = '未设置任务';
        }
        resReturn([
            'month_count' => $month_count,
            'month_price' => $month_price,
            'all_count' => $all_count,
            'all_price' => $all_price,
            'rate' => $rate,
        ]);
    }
    
    //今日客户跟进
    public function todayIndex(){
        $admin_id = input('admin_id');
        // $model = RecruitCustomer::where('admin_id', $admin_id)
        //     ->where()
        //已成交
        $list['closed'] = RecruitCustomer::where('admin_id', $admin_id)
            ->whereDay('update_time')
            ->where('customer_type', 5)
            ->count();
            //已到访
        $list['visited'] = RecruitCustomer::where('admin_id', $admin_id)
            ->whereDay('update_time')
            ->where('customer_type',3)
            ->count();
            //已邀约
        $list['invited'] = RecruitCustomer::where('admin_id', $admin_id)
            ->whereDay('update_time')
            ->where('customer_type',2)
            ->count();
            //应跟进
        $list['should_follow'] = RecruitCustomerPhone::where('admin_id', $admin_id)
            ->whereIn('invite_type',[3,4])
            ->whereDay('update_time')
            ->count();
        resReturn($list);
    }
    /**
     * 团队任务
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recruitDirector()
    {
        $admin_id = input('param.admin_id');
        $admin = AdminAdmin::where('top_id', $admin_id)->column('id');
        $admin[] = $admin_id;
        // 获取本月信息
        $task = SchoolTeamTask::where('admin_id', $admin_id)
            ->where('month', toDate(time(), 'Y-m'))
            ->find();
        $month_count = RecruitCustomer::whereIn('admin_id', $admin)
            ->whereTime('deal_time', 'month')
            ->count();
        $month_price = RecruitCustomer::whereIn('admin_id', $admin)
            ->whereTime('deal_time', 'month')
            ->sum('deal_price');
        $all_count = RecruitCustomer::whereIn('admin_id', $admin)
            ->where('deal_price', '>', 0)
            ->count();
        $all_price = RecruitCustomer::whereIn('admin_id', $admin)
            ->where('deal_price', '>', 0)
            ->sum('deal_price');
        resReturn([
            'month_count' => $month_count,
            'month_price' => $month_price,
            'all_count' => $all_count,
            'all_price' => $all_price,
            'task' => $task ,
        ]);
    }



    

    /**
     * 获取客户来源
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function customerSource()
    {
        $id = input('param.id');
        $admin = AdminAdmin::where('id', $id)->find();
        $list  = SchoolCustomerSource::field('id,source_info')
        ->where('school_id', $admin['school_id'])
            ->select();
        resReturn($list);
    }

    /**
     * 客户录入
     */
    public function customerAdd()
    {

        $data = input('param.');
        Db::startTrans();
        try {
            $parent = [
//                'mobile' => $data['mobile'],
                'username' => $data['username'],
                'relationship' => $data['relationship'],
//                'age' => $data['age'],
                'source_id' => $data['source_id'],
                'intention' => $data['intention'],
                'user_type' => $data['user_type'],
                'home_mobile' => $data['home_mobile'],
//                'address' => $data['address'],
                'address_info' => $data['address_info'],
                'admin_id' => $data['admin_id'],
                'create_time' => toDate(time()),
            ];

            $top_id = RecruitCustomer::insertGetId($parent);
            $children = json_decode($data['children'], true);
            $child = [];
            foreach ($children as $v) {
                $child[] = [
                    'customer_id' => $top_id,
                    'username' => $v['username'],
                    'birthday' => $v['birthday'],
                    'sex' => $v['sex'],
                    'body_img' => $v['body_img'],
                ];
            }
            RecruitCustomerBody::insertAll($child);
            Db::commit();
            resReturn('', '录入成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            resReturn('', $e->getMessage(), 101);
        }
    }
    /**
     * 客户录入修改
     */
    public function customerEdit()
    {

        $data = input('param.');
        Db::startTrans();
        try {
            $parent = [
//                'mobile' => $data['mobile'],
                'username' => $data['username'],
                'relationship' => $data['relationship'],
//                'age' => $data['age'],
                'source_id' => $data['source_id'],
                'intention' => $data['intention'],
                'user_type' => $data['user_type'],
                'home_mobile' => $data['home_mobile'],
//                'address' => $data['address'],
                'address_info' => $data['address_info'],
                'admin_id' => $data['admin_id'],
                'create_time' => toDate(time()),
            ];

            $top_id = RecruitCustomer::where('id',$data['id'])->update($parent);
            //删除宝宝信息
            RecruitCustomerBody::where('customer_id',$top_id)->delete();
            $children = json_decode($data['children'], true);
            $child = [];
            foreach ($children as $v) {
                $child[] = [
                    'customer_id' => $top_id,
                    'username' => $v['username'],
                    'birthday' => $v['birthday'],
                    'sex' => $v['sex'],
                    'body_img' => $v['body_img'],
                ];
            }
            RecruitCustomerBody::insertAll($child);
            Db::commit();
            resReturn('', '录入成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            resReturn('', $e->getMessage(), 101);
        }
    }

    /**
     * 今日录入的客户
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function customerToday()
    {
        $admin_id = input('param.admin_id');
        $list = RecruitCustomer::where([
            'admin_id' => $admin_id
        ])
            ->whereTime('create_time', 'today')
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['child'] = RecruitCustomerBody::where('customer_id', $v['id'])->select();
            $time = strtotime($v['create_time']);
            $now_hour = toDate($time, 'H');
            if ($now_hour > 12) {
                $list[$k]['time'] = '下午';
                $list[$k]['hour'] = ($now_hour - 12) .':'. toDate($time, 'i');
            } else {
                $list[$k]['time'] = '上午';
                $list[$k]['hour'] = toDate($time, 'H:i');
            }
        }
        resReturn($list);
    }

    /**
     * 客户详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function customerDetail()
    {
        $id = input('param.id');
        $list = RecruitCustomer::with([
            'get_source' => function($a) {
                 $a->field('id,source_info');
            }
        ])->where([
            'id' => $id
        ])
            ->find();
        $child = RecruitCustomerBody::where('customer_id', $id)->select();
        foreach ($child as $k => $v) {
            $start_time = strtotime($v['birthday']);
            $end_time = time();
            $diff = abs($end_time - $start_time);
            $years = floor($diff / (365*60*60*24));
            $months = floor(($diff - $years * 365*60*60*24)  / (30*60*60*24));
            $days = floor(($diff - $years * 365*60*60*24 -  $months*30*60*60*24)/ (60*60*24));
            $child[$k]['time'] = $years.'岁'.$months.'月'.$days.'日';
        }
        $list['child'] = $child;
        resReturn($list);
    }

    /**
     * 邀约客户
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function customerInvite()
    {
        $admin_id = input('param.admin_id');
        $list = RecruitCustomer::where([
            'admin_id' => $admin_id,
            'customer_type' => 1,
        ])
            ->whereTime('create_time', 'today')
            ->select();
        foreach ($list as $k => $v) {
            $list[$k]['child'] = RecruitCustomerBody::where('customer_id', $v['id'])
                ->order('id desc')
                ->select();
        }
        resReturn($list);
    }

    /**
     * 电话回访
     */
    public function customerPhone()
    {
        $data = input('param.');
        Db::startTrans();
        try {
            RecruitCustomerPhone::create([
                'customer_id' => $data['id'],
                'status' => $data['status'],
                'admin_id' => $data['admin_id'],
                'phone_note' => $data['phone_note'],
                'invite_time' => strtotime(isset($data['invite_time']) ? $data['invite_time'] : toDate(time())),
                'create_time' => toDate(time()),
            ]);
            if ($data['status'] == 2) {
                RecruitCustomer::where('id', $data['id'])
                    ->update([
                        'customer_type' => 2
                    ]);
            }
            Db::commit();
            resReturn('', '录入成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            resReturn('', $e->getMessage(), 101);
        }
    }

    /**
     * 应到客户列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function shouldVisit()
    {
        $admin_id = input('param.admin_id');
        $invite_type = input('param.invite_type', 1);
        $username = input('param.username', '');
        $where[] = ['status','=',2];
        if($username){
            $where[] = ['b.username|c.username','like','%'.$username.'%'];
        }
        $list = RecruitCustomerPhone::where('a.admin_id', $admin_id)
            ->alias('a')
            ->field('a.*')
            ->join('bl_recruit_customer_body b','a.customer_id=b.customer_id','left')
            ->join('bl_recruit_customer c','a.customer_id=c.id','left')
            ->where('invite_type', $invite_type)
            ->where($where)
            ->order('a.id desc')
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['invite_time'] = toDate($value['invite_time']);
            $list[$key]['customer'] = RecruitCustomer::with([
                'get_source' => function($a) {
                    $a->field('id,source_info');
                }
            ])->where([
                'id' => $value['customer_id']
            ])
                ->find();
            $child = RecruitCustomerBody::where('customer_id', $value['customer_id'])->select();
            foreach ($child as $k => $v) {
                $list[$key]['child'] = RecruitCustomerBody::where('customer_id', $value['customer_id'])->select();
            }
        }
        resReturn($list, '获取成功');
    }

    /**
     * 跟进计划
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function visitPlan()
    {
        $admin_id = input('param.admin_id');
        $list = RecruitCustomerPhone::where('admin_id', $admin_id)
            ->whereIn('invite_type', [3,4])
            ->order('id desc')
            ->select();
        foreach ($list as $key => $value) {
            $list[$key]['invite_time'] = toDate($value['invite_time']);
            $list[$key]['customer'] = RecruitCustomer::with([
                'get_source' => function($a) {
                    $a->field('id,source_info');
                }
            ])->where([
                'id' => $value['customer_id']
            ])
                ->find();
            $child = RecruitCustomerBody::where('customer_id', $value['customer_id'])->select();
            foreach ($child as $k => $v) {
                $list[$key]['child'] = RecruitCustomerBody::where('customer_id', $value['customer_id'])->select();
            }
        }
        resReturn($list, '获取成功');
    }
    
    /**
     * 跟进次数
     */
    public function visitCount()
    {
        $id = input('param.id');
        $phone = RecruitCustomerPhone::where('id', $id)->value('visit_count');
        resReturn($phone);
    }

    /**
     * 录入跟进
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function visitInput()
    {
        $data = input('param.');
        RecruitCustomerPhone::where('id', $data['id'])->inc('visit_count', 1)->update();
        $phone = RecruitCustomerPhone::where('id', $data['id'])->find();
        if ($data['invite_type'] == 2) {
            RecruitCustomer::where('id', $phone['customer_id'])
                ->update([
                    'customer_type' => 3
                ]);
        } else if ($data['invite_type'] == 3) {
            RecruitCustomer::where('id', $phone['customer_id'])
                ->update([
                    'customer_type' => 4
                ]);
        } else if ($data['invite_type'] == 4) {
            //  4=未成交
            RecruitCustomer::where('id', $phone['customer_id'])
                ->update([
                    'customer_type' => 1
                ]);
        } else if ($data['invite_type'] == 5) {
            //  4=未成交
            RecruitCustomer::where('id', $phone['customer_id'])
                ->update([
                    'customer_type' => 5,
                    'deal_price' => $data['deal_price'],
                    'deal_time' => toDate(time()),
                    'renewal_time' => $data['renewal_time'],
                ]);
        } else {
            //  已成交
            resReturn('', '录入失败', 101);
        }
        RecruitCustomerPhone::where('id', $data['id'])->update([
            'invite_time' => strtotime($data['invite_time']),
            'invite_type' => $data['invite_type'],
            'phone_note' => $data['phone_note'],
        ]) ?  resReturn('', '录入成功') : resReturn('', '录入失败', 101);
    }

    /**
     * 成交的客户
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function customerDeal()
    {
        $admin_id = input('param.admin_id');
        $where = [];
//        //按客户意向查找
//        if ($intention = input("intention")) {
//            $where[] = ["intention", "like", "%" . $intention . "%"];
//        }
        if ($username = input("username")) {
            $where[] = ["username|intention","like", "%" . $username . "%"];
        }
//        if ($source_id = input("source_id")) {
//            $where[] = ["source_id", "=",  $source_id ];
//        }
        $list = RecruitCustomer::where([
            'admin_id' => $admin_id
        ])
            ->where($where)
            ->where('customer_type', 5)
            ->select();
        foreach ($list as $k => $v) {
            $child = RecruitCustomerBody::where('customer_id', $v['id'])->select();
            foreach ($child as $key => $value) {
                if ($value['student_id'] > 0) {
                    $child[$key]['child'] = StudyStudentList::where('id',$value['student_id'])->find();
                } else {
                    $child[$key]['child'] = [];
                }
            }
            $list[$k]['child'] = $child;
        }
        resReturn($list);
    }

    /**
     * 获取学生列表 SchoolWorkerTask
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function studentList()
    {
        $admin_id = input('param.admin_id');
        $all = AdminAdmin::where('top_id', $admin_id)->column('id');
        $all[] = $admin_id;
        $list = RecruitCustomer::with([
            'get_admin' => function($a) {
                $a->field('id,username');
            }
        ])->whereIn('admin_id', $all)
            ->where('customer_type', 5)
            ->select();
        foreach ($list as $k => $v) {
            $body = RecruitCustomerBody::where('customer_id', $v['id'])
                ->where('student_id', '>', 0)
                ->column('student_id');
            if ($body) {
                $list[$k]['student'] = StudyStudentList::field("id,username,sex,nursery_time,mobile,student_img,FROM_UNIXTIME(end_time,'%Y-%m-%d') as end_time")->whereIn('id', $body)->select();
            } else {
                unset($list[$k]);
            }

        }
       resReturn($list);
    }
    
    public function visited(){
        $id = input('param.id');
        $modelData = RecruitCustomerPhone::find($id);
        $modelData->invite_type=2;
        $modelData->save();
        if(RecruitCustomer::where(['id'=>$modelData->customer_id])->update(['customer_type'=>3])){
            resReturn('','成功');
        }else{
            resReturn('','失败');
        }
    }


}